#define _CRT_SECURE_NO_WARNINGS 1
#include "Tree.h"
#include "Queue.h"
BTNode* BuyNode(int index)
{
	BTNode* buynode = (BTNode*)malloc(sizeof(BTNode));
	if (buynode == NULL)
	{
		perror("malloc error!\n");
		exit(1);
	}
	buynode->value = index;
	buynode->left = NULL;
	buynode->right = NULL;
	return buynode;
}
void preOrder(BTNode* root)
{
	if (root == NULL)
		return;
	printf("%d ", root->value);
	preOrder(root->left);
	preOrder(root->right);
}
void InOrder(BTNode* root)
{
	if (root == NULL)
		return;
	InOrder(root->left);
	printf("%d ", root->value);
	InOrder(root->right);
}
void PostOrder(BTNode* root)
{
	if (root == NULL)
		return;
	PostOrder(root->left);
	PostOrder(root->right);
	printf("%d ", root->value);
}
int BinaryTreeSize(BTNode* root)
{
	if (root == NULL)
		return 0;
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}
int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
		return 0;
	if (root->left == NULL && root->right == NULL)
		return 1;
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}
int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (root == NULL)
		return 0;
	if (k == 1)
		return 1;
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}
int BinaryTreeDepth(BTNode* root)
{
	if (root == NULL)
		return 0;
	int leftDep = BinaryTreeDepth(root->left);
	int rightDep = BinaryTreeDepth(root->right);
	return leftDep > rightDep ? leftDep + 1 : rightDep + 1;
}
BTNode* BinaryTreeFind(BTNode* root, int x)
{
	if (root == NULL)
		return NULL;
	if (root->value == x)
		return root;
	BTNode* leftFind = BinaryTreeFind(root->left, x);
	if (leftFind)
		return leftFind;
	BTNode* rightFind = BinaryTreeFind(root->right, x);
	if (rightFind)
		return rightFind;
	return NULL;

}
void BinaryTreeDestory(BTNode** root)
{
	if (*root == NULL)
		return;
	BinaryTreeDestory(&((*root)->left));
	BinaryTreeDestory(&((*root)->right));
	free(*root);
	*root = NULL;
}
bool BinaryTreeComplete(BTNode* root)
{
	Queue q;
	QueueInit(&q);
	QueuePush(&q, root);
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);
		if (front == NULL) break;
		QueuePush(&q, front->left);
		QueuePush(&q, front->right);
	}
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);
		if (front != NULL)
		{
			QueueDestroy(&q);
			return false;
		}
	}
	QueueDestroy(&q);
	return true;
}
void LevelOrder(BTNode* root)
{
	Queue q;
	QueueInit(&q);
	QueuePush(&q,root);
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		printf("%d ", front->value);
		QueuePop(&q);
		if (front->left)
			QueuePush(&q, front->left);
		if (front->right)
			QueuePush(&q, front->right);
	}
	QueueDestroy(&q);
}